package com.ts.zuul.gateway.filter;

import com.netflix.zuul.ZuulFilter;
import com.netflix.zuul.context.RequestContext;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Component;

import javax.servlet.ServletInputStream;
import javax.servlet.http.HttpServletRequest;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.UUID;


/**
 * Created by Zhou_Bing on 2018/9/6.
 */
@Component
public class ReqLogFilter extends ZuulFilter{

    private static final Logger logger =LoggerFactory.getLogger(ReqLogFilter.class);

    @Override
    public String filterType() {
        return "pre";
    }

    @Override
    public int filterOrder() {
        return -20;
    }

    @Override
    public boolean shouldFilter() {
        return true;
    }

    @Override
    public Object run() {
        RequestContext ctx = RequestContext.getCurrentContext();

        HttpServletRequest request = ctx.getRequest();

        String reqId =  UUID.randomUUID().toString().replace("-","");
        request.setAttribute("reqId",reqId);

        logger.info(String.format("request %s:: send %srequest to %s  %s",reqId,request.getMethod(),request.getRequestURL().toString(),request.getProtocol()));

        //输出所有参数
        request.getParameterMap().keySet().forEach(a->{
            StringBuilder values = new StringBuilder();
            for(String value:request.getParameterMap().get(a)){
                values.append(value+",");
            }
            logger.info("request "+reqId+":: param "+a+":"+(values.length()>0?values.substring(0,values.length()-1):values.toString()));
        });

        if (!ctx.isChunkedRequestBody()) {
            ServletInputStream inp = null;
            try {
                inp = ctx.getRequest().getInputStream();
                StringBuilder body = new StringBuilder();
                if (inp != null) {
                    BufferedReader reader = new BufferedReader(new InputStreamReader(inp));

                    String line = "";
                    while((line = reader.readLine()) != null){//一行一行的读取body体里面的内容；
                        body.append(line);
                    }
                    logger.info("request "+reqId+":: body:"+body.toString());
                }
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        return null;
    }
}
